package cn.cs.service.impl;


import cn.cs.client.*;
import cn.cs.common.BigDecimalUtil;
import cn.cs.common.EmptyUtils;
import cn.cs.common.IdWorker;
import cn.cs.common.JPushUtil;
import cn.cs.pojo.AppOrder;
import cn.cs.pojo.ClientUser;
import cn.cs.pojo.CsProportionSetting;
import cn.cs.pojo.QgTrade;
import cn.cs.service.QgWxpayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author  yuexl
 */
@Service
public class QgWxpayServiceImpl implements QgWxpayService {
    private static final Logger logger = LoggerFactory.getLogger(QgWxpayServiceImpl.class);


    @Resource
    private QgTradeClient qgTradeClient;

    @Resource
    private AccountDetailClient accountDetailClient;

    @Resource
    private RestRepairOrderClient restRepairOrderClient;

    @Resource
    private RestClientUserClient clientUserClient;

    @Resource
    private UserBalanceClient userBalanceClient;

    @Resource
    private CsProportionSettingClient proportionSettingClient;

    @Resource
    private RestAppOrderClient appOrderClient;

    @Resource
    private SysDtAreaClient sysDtAreaClient;

    @Resource
    private AgentClient agentClient;

    @Resource
    private RestRepairUserClient repairUserClient;

    @Override
    public Integer insertTrade(String orderNo, String tradeNo, String userId, String amount, String type) throws Exception {
        QgTrade qgTrade = new QgTrade();
        qgTrade.setId(IdWorker.getId());
        qgTrade.setOrderNo(orderNo);
        qgTrade.setTradeNo(tradeNo);
        qgTrade.setUserId(userId);
        qgTrade.setPayMethod(2);
        qgTrade.setAmount(Double.valueOf(amount));
        qgTrade.setCreatedTime(new Date());
        qgTrade.setCreatedTime(new Date());
        qgTrade.setType(type);
        qgTradeClient.insertQgTrade(qgTrade);
        return 1;
    }


    @Override
    public Map<String, Object> processed(String orderNo, String attach) throws Exception {
        Map<String, Object> map = null;
        if("recharge".equals(attach)){//充值
            map = accountDetailClient.getAccountDetailById(orderNo);
        }else if("order".equals(attach)){//订单支付
            map = restRepairOrderClient.getOrderById(orderNo);
        }else if("test_report".equals(attach)){//检测报告支付
            map = restRepairOrderClient.getTestReportById(orderNo);
        }
        return map;
    }

    public Integer updateOrderStatus(Map<String, Object> map, String attach) throws Exception{
        int i = 0;
        if("recharge".equals(attach)){

            String userId = map.get("userId").toString();
            ClientUser user = clientUserClient.getClientUserById(userId);

            Double oldBalance = user.getBalance();
            Double balance = Double.valueOf(map.get("amount").toString());
            Double b = BigDecimalUtil.OperationASMD(oldBalance,balance, BigDecimalUtil.BigDecimalOprations.add,2, BigDecimal.ROUND_HALF_UP).doubleValue();
            logger.info("b-----------------------------------------" + b);
            i = accountDetailClient.updateAccountStatus(map.get("id").toString(), b);
            logger.info("i-----------------------------------------" + i);
            if(i >= 1){
                userBalanceClient.modifyUserBalance(String.valueOf(b), userId);
            }



        }else if("order".equals(attach)){

            String rep_user_id = map.get("rep_user_id").toString();
            List<Map<String, Object>> mapList = restRepairOrderClient.getOrderByRepUserId(rep_user_id);
            //mapList <= 0 维修工 当天第一次被支付订单
            String key = "userPayToRepairUser";
            String val = "0";
            if(mapList.size() <= 0){
                CsProportionSetting map1 = proportionSettingClient.getCsProportionSettingById("1");
                Double insurancePremium = Double.valueOf(map1.getInsurancePremium());
                Double proportionPlatform = Double.valueOf(map1.getProportionPlatform());
                Double proportionProvince = Double.valueOf(map1.getProportionProvince());
                Double proportionCity = Double.valueOf(map1.getProportionCity());
                Double all_cost = Double.valueOf(map.get("amount").toString());
                Double tax = Double.valueOf(map.get("tax").toString());
                Double earning = all_cost - tax;//先扣除税费
                earning = earning - insurancePremium; //再扣除保险费
                proportionPlatform = proportionPlatform * earning;
                proportionProvince = proportionProvince * earning;
                proportionCity = proportionCity * earning;

                earning = earning - proportionPlatform - proportionProvince - proportionCity;

                Map<String, Object> map2 = new HashMap<>();
                map2.put("all_cost", map.get("amount").toString());
                map2.put("earPlatform", new BigDecimal(proportionPlatform).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                map2.put("earProvince", new BigDecimal(proportionProvince).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                map2.put("earCity", new BigDecimal(proportionCity).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                map2.put("earning", new BigDecimal(earning).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                map2.put("insurance_premium", map1.getInsurancePremium());
                map2.put("rep_order_id", map.get("id").toString());
                map2.put("order_state", "3");
                map2.put("peopleCost", map.get("peopleCost").toString());
                map2.put("pay_type", "0");
                map2.put("agentAId", null);
                map2.put("agentBId", null);

                i = restRepairOrderClient.updateRepOrderStatusMoney(map2);
                key = "repairUserInsurancePremium";
                val = map1.getInsurancePremium();

            }

            //获取本订单的省级会长，以及市县级经理
            AppOrder appOrder = appOrderClient.getAppOrderById(map.get("app_order_id").toString());
            String area = appOrder.getAreaId();
            Map<String, Object> areaLast = sysDtAreaClient.getAreaLastById(area);
            if(EmptyUtils.isNotEmpty(areaLast)){
                area = areaLast.get("area_parent_id").toString();
            }
            List<Map<String, Object>> agentByArea = agentClient.getAgentByArea(area);
            String agentAId = "", agentBId = "";
            for(Map<String, Object> a:agentByArea){
                if("1".equals(a.get("type_id").toString())){
                    agentAId = a.get("id").toString();
                }else if("2".equals(a.get("type_id").toString())){
                    agentBId = a.get("id").toString();
                }
            }



            i = restRepairOrderClient.updateOrderStatus(map.get("id").toString(),map.get("app_order_id").toString(), agentAId, agentBId);

            //修改维修工接单数量
            repairUserClient.updateUserOrderNumber(rep_user_id);
            // 发送极光推送给维修工
            String[] strSelect = new String[1];
            Map<String, String> cmap = new HashMap<String, String>();
            cmap.put(key, val);
            strSelect[0] = rep_user_id;
            Object obj = JPushUtil.testSendPush(strSelect, "用户支付订单成功，请查看", cmap);
            System.out.println(obj);

        }else if("test_report".equals(attach)){
            String rep_user_id = map.get("rep_user_id").toString();

            //经销商平台抽成   --- 暂时不要，屏蔽
            Double testCost = Double.valueOf(map.get("testCost").toString());
            CsProportionSetting map1 = proportionSettingClient.getCsProportionSettingById("1");
            Double proportionPlatform = Double.valueOf(map1.getProportionPlatform());
            Double proportionProvince = Double.valueOf(map1.getProportionProvince());
            Double proportionCity = Double.valueOf(map1.getProportionCity());
            Double insurancePremium = Double.valueOf(map1.getInsurancePremium());

            proportionPlatform = proportionPlatform * testCost;
            proportionProvince = proportionProvince * testCost;
            proportionCity = proportionCity * testCost;

            List<Map<String, Object>> mapList = restRepairOrderClient.getOrderByRepUserId(rep_user_id);
            //mapList <= 0 维修工 当天第一次被支付订单
            String key = "userPayTestReportToRepairUser";
            String val = "0";
            Double earning = testCost;
            Map<String, Object> map2 = new HashMap<>();
            if(mapList.size() <= 0){
                earning = earning - insurancePremium;
                key = "testReportToRepairUserIP";
                map2.put("insurance_premium", map1.getInsurancePremium());
                val = map1.getInsurancePremium();
            }else{
                map2.put("insurance_premium", "0");
            }

            map2.put("all_cost", map.get("testCost"));

            map2.put("earPlatform", "0");
            map2.put("earProvince", "0");
            map2.put("earCity", "0");
            map2.put("earning", earning);

            map2.put("order_state", "6");
            map2.put("peopleCost", map.get("testCost"));
            map2.put("rep_order_id",map.get("rep_order_id").toString());
            map2.put("agentAId", null);
            map2.put("agentBId", null);
            i = restRepairOrderClient.updateRepOrderStatusMoney(map2);

            i = restRepairOrderClient.updateTestReportStatus(map.get("rep_order_id").toString(),map.get("app_order_id").toString(),map.get("id").toString());

            // 发送极光推送给维修工
            String[] strSelect = new String[1];
            Map<String, String> cmap = new HashMap<String, String>();
            cmap.put(key, val);
            strSelect[0] = rep_user_id;
            Object obj = JPushUtil.testSendPush(strSelect, "用户支付检测费成功，请查看", cmap);
            System.out.println(obj);
        }
        return i;
    }

    public Integer updateMoneyByType(String money, String type)throws Exception{
        return qgTradeClient.updateMoneyByType(money, type);
    }

    public Map<String, Object> getFundsAccountByType(String type)throws Exception{
        return qgTradeClient.getFundsAccountByType(type);
    }

    public Integer saveFundsCarryOver(Map<String, Object> map)throws Exception{
        return qgTradeClient.saveFundsCarryOver(map);
    }

    public List<Map<String, Object>> getFundsCarryOverByType(String type)throws Exception{
        return qgTradeClient.getFundsCarryOverByType(type);
    }

}
